package com.unionbigdata.teaching.sevice.impl;

import com.unionbigdata.teaching.entity.UserEntity;
import com.unionbigdata.teaching.mapper.UserMapper;
import com.unionbigdata.teaching.sevice.IUserService;
import com.unionbigdata.teaching.vo.UserVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;


    @Override
    public UserVO findById(Long id) {
        UserEntity userEntity = userMapper.selectById(id);
        return convertUserVO(userEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveUser(UserVO userVO) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName(userVO.getName());
        userEntity.setAge(userVO.getAge());
        userEntity.setGender(userVO.getGender());
        userMapper.insert(userEntity);
        return userEntity.getId();
    }

    @Override
    public List<UserVO> findUserList() {
        List<UserEntity> userList = userMapper.findUserList();
        return userList.stream().map(this::convertUserVO).toList();
    }

    private UserVO convertUserVO(UserEntity userEntity) {
        UserVO userVO = new UserVO();
        if (!ObjectUtils.isEmpty(userEntity)) {
            userVO.setId(userEntity.getId());
            userVO.setName(userEntity.getName());
            userVO.setAge(userEntity.getAge());
            userVO.setGender(userEntity.getGender());
        }
        return userVO;
    }


}
